package com.app.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import com.app.activity.ActivityBase;


public abstract class BaseFragment extends Fragment {


    private String title;

    protected boolean isCreated = false;
    protected boolean isVisible = false;

    protected BackHandledInterface mBackHandledInterface;

    public abstract boolean onBackPressed();

    public BaseFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(!(getActivity() instanceof BackHandledInterface)){
            throw new ClassCastException("Hosting Activity must implement BackHandledInterface");
        }else{
            this.mBackHandledInterface = (BackHandledInterface)getActivity();
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (isCreated == false) {
            isCreated = true;
            if (isVisible) {
                initTitle();
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    protected void setTitle(String title) {
        this.title = title;
    }

    private void initTitle() {
        if (title != null && !title.equals("")) {
            ((ActivityBase) getActivity()).setTitle(title);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        isVisible = isVisibleToUser;
        if (isVisibleToUser && isCreated) {
            initTitle();
            mBackHandledInterface.setSelectedFragment(this);
        }
        super.setUserVisibleHint(isVisibleToUser);
    }



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

}
